package com.eorchis.module.classnotice.dao.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.stereotype.Repository;
import org.springframework.util.FileCopyUtils;

import com.eorchis.core.basedao.dao.impl.HibernateAbstractBaseDao;
import com.eorchis.core.basedao.entity.IBaseEntity;
import com.eorchis.core.basedao.query.condition.builder.CompareType;
import com.eorchis.core.basedao.query.condition.builder.IConditionBuilder;
import com.eorchis.core.page.commond.SortInfoBean;
import com.eorchis.core.ui.commond.IQueryCommond;
import com.eorchis.module.classnotice.dao.IClassNoticeDao;
import com.eorchis.module.classnotice.domain.ClassNotice;
import com.eorchis.module.classnotice.querybean.ClassNoticeQueryBean;
import com.eorchis.module.classnotice.ui.commond.ClassNoticeQueryCommond;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: ClassNoticeDaoImpl<br>
 * Description: 入学通知数据接口实现<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * @author Max
 * @createDate 2014-12-12
 * @version $Revision$
 */
@SuppressWarnings("unchecked")
@Repository(value = "com.eorchis.module.classnotice.dao.impl.ClassNoticeDaoImpl")
public class ClassNoticeDaoImpl
					extends HibernateAbstractBaseDao
					implements IClassNoticeDao {
	
	public Class<? extends IBaseEntity> entityClass() {
		return ClassNotice.class;
	}
	
	@Autowired
	@Qualifier("com.eorchis.module.schedule.dao.impl.ScheduleDaoImpl")
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private LobHandler lobHandler;
	
	public void queryConditionProcessor(
			IConditionBuilder defaultQueryConditionBuilder,
			IQueryCommond queryCommond) {
		ClassNoticeQueryCommond classNoticeQueryCommond = (ClassNoticeQueryCommond)queryCommond;
		defaultQueryConditionBuilder.setBaseQueryString("SELECT t FROM ClassNotice t");
		defaultQueryConditionBuilder.addCondition("t.noticeId", CompareType.IN, classNoticeQueryCommond.getSearchNoticeIds());
		defaultQueryConditionBuilder.addCondition("t.noticeId", CompareType.EQUAL,classNoticeQueryCommond.getSearchNoticeId());
		defaultQueryConditionBuilder.setQueryStringType(QueryStringType.HQL);
	}
	
	/**
	 * 查询班级入学通知
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2014-12-12
	 */
	@Override
	public List<ClassNoticeQueryBean> findClassNoticeAllList(ClassNoticeQueryCommond 
			qCommond) throws Exception {
		
		//拼写查询的sql
		StringBuffer hql = new StringBuffer();
		hql.append("select c.noticeId as noticeId,c.attachmentId as attachmentId,t.primevalFileName as fileName,c.trainingClass.classId as classId");
		hql.append(" FROM ClassNotice c,Attachment t  where c.attachmentId=t.attachmentID");
		//拼写查询条件sql begin
		Map<String, Object> values = new HashMap<String, Object>();
		//班级id
		if(PropertyUtil.objectNotEmpty(qCommond.getSearchClassId())){
			hql.append(" and c.trainingClass.classId = :classId ");
			values.put("classId", qCommond.getSearchClassId().trim());
		}
		
		List<SortInfoBean> sortInfoList = qCommond.getSortInfo();
		if (sortInfoList != null && sortInfoList.size() > 0) {
			SortInfoBean sortInfo = sortInfoList.get(0);
			hql.append(" order by " + PropertyUtil.sqlInjectionFilter(sortInfo.getProperty()) + " " + PropertyUtil.sqlInjectionFilter(sortInfo.getDirection()));
		} else {
			hql.append(" order by c.noticeId desc");
		}
		
		return (List<ClassNoticeQueryBean>) this.executeFind(QueryStringType.HQL, hql.toString(), values, ClassNoticeQueryBean.class);
	}
	/**
	 * 查询附件文件流
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2014-12-12
	 */
	@Override
	public byte[] getFileblob(ClassNoticeQueryCommond qCommond) throws Exception {
		String sql = "select t.content from Base_Attachment t where t.attachment_id = ? ";
		String attachmentId = qCommond.getSearchAttachMentId();
		final ByteArrayOutputStream output=new ByteArrayOutputStream();
		jdbcTemplate.query(sql, new String[] {attachmentId},new AbstractLobStreamingResultSetExtractor() {
			protected void streamData(ResultSet rs) throws SQLException, IOException,
					DataAccessException {
				InputStream	inputStream = lobHandler.getBlobAsBinaryStream(rs, 1);
			    byte[] b = new byte[4096];
			    int n = 0;
			    if(inputStream!=null){
			    while (-1 != (n = inputStream.read(b))) {
			        output.write(b, 0, n);
			    } 
			    }
			}
		});
		return output.toByteArray();
	}

	@Override
	public String getFileName(ClassNoticeQueryCommond qCommond)
			throws Exception {
		String sql = "select t.PRIMEVAL_FILE_NAME from Base_Attachment t where t.attachment_id = :attaId ";
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("attaId",qCommond.getSearchAttachMentId());
		return this.executeFind(QueryStringType.SQL, sql, params).get(0).toString();
	}
}
